Skip to main content

PHP/Twig Queries

Sample queries that devs can use to quickly loop through something

PHP

// Grabbing blog posts. Change to CPT if needed
$args = array(
'post_type' => 'post',
'posts_per_page' => get_option('posts_per_page', 9),
'order' => 'DESC',
'paged' => $paged
);

// Creating a variable for taxonomy
$context['taxonomy'] = "category";

$context['items'] = new Timber\PostQuery( $args );
$context['pagination' ] = Timber::get_pagination();

Twig

{#############################################################}
{# Start #}
{#############################################################}

<!-- Allow WP user to manually select the entries to output through a ACF relationship field -->
{% if section.manual_post_selector %}
{% set items = section.items %}

<!-- No manual selection? Let's show the latest X amount of posts instead. In this case the blog posts -->
{% else %}
{% set items = function( 'get_cpt_posts_by',
'post',
3,
'post_date',
'DESC',
post.ID
) %}
{% endif %}

<!-- Looping through either the manual or automatic selection -->
{% for item in items %}

{# Accessing WordPress post and making them available to Twig templates #}
{% set item = TimberPost( item ) %}

{# Accessing WordPress image object and making them available to Twig templates #}
{% set img = TimberImage( item.thumbnail ) %}

{# Give pretitle the post type name value #}
{% set pretitle = item.type.labels.singular_name %}

{# Hack to ensure post gets renamed to blog without modifying the Post post type #}
{% if pretitle == "Post" %}
{% set pretitle = "Blog" %}
{% endif %}

{% include '02-molecules/cards/card-post/card-post.twig' with {
parent_class : component_class,
item : item,
img : img,
interval : true,
index : loop.index,
add_class_in_view : true,
} only %}
{% endfor %}

{#############################################################}
{# END #}
{#############################################################}